package com.etc.library.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.List;

public class JWTUtil {

    //超时时间
    private static final long EXPIRE_TIME = 1000*60*60*24;

    /*秘钥*/
    private static final String SECRET = "1qa*z2!wsx@";


    /**
     * 生成token
     * @param userId
     * @return
     */
    public static String generateToken(Integer userId,Integer role){
        Date expireDate = new Date(System.currentTimeMillis()+EXPIRE_TIME);
        String token = JWT.create().withAudience(String.valueOf(userId),String.valueOf(role)).withExpiresAt(expireDate )
                .sign(Algorithm.HMAC256(SECRET));
        return token;
    }


    /**
     * 校验token是否合法
     * @param token
     * @return
     */
    public static boolean checkToken(String token) {
        try {
            DecodedJWT verify = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
            return true;
        } catch (AlgorithmMismatchException e){
            throw new AlgorithmMismatchException("算法不匹配");
        }catch (SignatureVerificationException e){
            throw  new RuntimeException("秘钥不正确");
        }catch (JWTVerificationException e) {
            throw new RuntimeException("token 无效");
        }catch (IllegalArgumentException e) {
            throw new RuntimeException("token 无效，请重新登录");
        }
    }

    /**
     * 解析token,获取信息
     * @param token
     * @return
     */
    public static List<String> parseToken(String token){
        return JWT.decode(token).getAudience();
    }
}
